package meta

import (
	"strconv"
	"time"
	"proxy/api"
)

type Rtc struct {
	Id         RtcId
	expireTime time.Time
}

func NewRtc(backendId int, rtcId int) *Rtc {
	return &Rtc{
		Id: RtcId{
			BackendId: backendId,
			RtcId:     rtcId,
		},
		expireTime: time.Now().Add(kRtcTimeout),
	}
}

func (r *Rtc) KeepAlive(now time.Time) {
	r.expireTime = now.Add(kRtcTimeout)
}

func (r *Rtc) IsExpired() bool {
	return time.Now().After(r.expireTime)
}

func (r *Rtc) Status() *api.RtcStatus {
	status := &api.RtcStatus{
		TTL: int(r.expireTime.Sub(time.Now()).Seconds()),
	}
	return status
}

//func (r *Rtc) Dump() {
//	log.Warningf("rtc: %d, ttl: %v", r.Id.Int(), r.expireTime.Sub(time.Now()))
//}

type RtcId struct {
	BackendId int
	RtcId     int
}

func ParseRtcId(text string) (RtcId, error) {
	id, err := strconv.Atoi(text)
	if err != nil {
		return RtcId{
			BackendId: -1,
			RtcId:     -1,
		}, err
	}

	return RtcId{
		BackendId: id / kRtcIdMax,
		RtcId:     id % kRtcIdMax,
	}, nil
}

func (id RtcId) Int() int {
	return id.BackendId*kRtcIdMax + id.RtcId
}
